package com.mapaower.admin.service;

import com.mapaower.admin.entity.AdminUser;
import com.mapaower.admin.repository.AdminUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class AdminUserService implements UserDetailsService {

    @Autowired
    private AdminUserRepository adminUserRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AdminUser adminUser = adminUserRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));

        // 更新最后登录时间
        adminUser.setLastLoginTime(new Date());
        adminUserRepository.save(adminUser);

        // 构建用户权限
        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
        adminUser.getRoles().forEach(role -> {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            role.getPermissions().forEach(permission -> {
                authorities.add(new SimpleGrantedAuthority(permission.getPermissionKey()));
            });
        });

        return new User(
                adminUser.getUsername(),
                adminUser.getPassword(),
                adminUser.getStatus() == AdminUser.AccountStatus.ACTIVE,
                true,
                true,
                true,
                authorities
        );
    }

    public AdminUser getAdminUserById(Long id) {
        return adminUserRepository.findById(id).orElse(null);
    }

    public AdminUser getAdminUserByUsername(String username) {
        return adminUserRepository.findByUsername(username).orElse(null);
    }

    public List<AdminUser> getAllAdminUsers() {
        return adminUserRepository.findAll();
    }

    public AdminUser createAdminUser(AdminUser adminUser) {
        if (adminUserRepository.existsByUsername(adminUser.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        if (adminUserRepository.existsByEmail(adminUser.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }

        // 加密密码
        adminUser.setPassword(passwordEncoder.encode(adminUser.getPassword()));
        // 默认状态为活跃
        adminUser.setStatus(AdminUser.AccountStatus.ACTIVE);

        return adminUserRepository.save(adminUser);
    }

    public AdminUser updateAdminUser(Long id, AdminUser adminUser) {
        AdminUser existingUser = getAdminUserById(id);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }

        // 更新用户信息
        if (adminUser.getUsername() != null && !adminUser.getUsername().equals(existingUser.getUsername())) {
            if (adminUserRepository.existsByUsername(adminUser.getUsername())) {
                throw new RuntimeException("用户名已存在");
            }
            existingUser.setUsername(adminUser.getUsername());
        }

        if (adminUser.getEmail() != null && !adminUser.getEmail().equals(existingUser.getEmail())) {
            if (adminUserRepository.existsByEmail(adminUser.getEmail())) {
                throw new RuntimeException("邮箱已存在");
            }
            existingUser.setEmail(adminUser.getEmail());
        }

        if (adminUser.getPhone() != null) {
            existingUser.setPhone(adminUser.getPhone());
        }

        if (adminUser.getStatus() != null) {
            existingUser.setStatus(adminUser.getStatus());
        }

        if (adminUser.getRoles() != null) {
            existingUser.setRoles(adminUser.getRoles());
        }

        return adminUserRepository.save(existingUser);
    }

    public boolean enableAdminUser(Long id) {
        AdminUser adminUser = getAdminUserById(id);
        if (adminUser == null) {
            return false;
        }
        adminUser.setStatus(AdminUser.AccountStatus.ACTIVE);
        adminUserRepository.save(adminUser);
        return true;
    }

    public boolean disableAdminUser(Long id) {
        AdminUser adminUser = getAdminUserById(id);
        if (adminUser == null) {
            return false;
        }
        adminUser.setStatus(AdminUser.AccountStatus.LOCKED);
        adminUserRepository.save(adminUser);
        return true;
    }

    public boolean deleteAdminUser(Long id) {
        AdminUser adminUser = getAdminUserById(id);
        if (adminUser == null) {
            return false;
        }
        adminUser.setStatus(AdminUser.AccountStatus.DELETED);
        adminUserRepository.save(adminUser);
        return true;
    }

    public boolean updatePassword(Long id, String oldPassword, String newPassword) {
        AdminUser adminUser = getAdminUserById(id);
        if (adminUser == null) {
            return false;
        }

        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, adminUser.getPassword())) {
            return false;
        }

        // 更新密码
        adminUser.setPassword(passwordEncoder.encode(newPassword));
        adminUserRepository.save(adminUser);
        return true;
    }
}